package cn.util.shiro.realm;

import cn.dao.CodePayDao;
import cn.mapper.MryeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.*;

public class MyRealm extends AuthorizingRealm{

	@Resource(name="mryeMapper")
	MryeMapper mryeMapper;

	/**
	 * 为当前登录的用户授予角色和权限
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String user_bh=(String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();

		authorizationInfo.setRoles(Collections.singleton("user"));

		Set<String> set=new HashSet();
			set.add("user");

		authorizationInfo.setStringPermissions(set);
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的用户
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String userbh=(String)token.getPrincipal();
		Map<String,Object> map=new HashMap<>();
		map.put("sql","SELECT a1.userbh,a1.userpwd, a1.username, a2.vipname FROM codeuser a1 LEFT JOIN vip a2 ON a1.viptype = a2.viptype WHERE a1.userbh = #{userbh} ");
		map.put("userbh",userbh);
		try {
			map=mryeMapper.searchSap(map);
		}catch (Exception e){
			System.out.println("------------"+e.getMessage());
		}
		if(map!=null){
			AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(map.get("userbh"),map.get("userpwd"),"xx");
			return authcInfo;
		}else{
			return null;
		}
	}
}


